package top.codetheory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeBuilder {
    public static void main(String[] args) {
        List<Map<String, Object>> nodes = new ArrayList<>();
        Map<String, Object> node1 = new HashMap<>();
        node1.put("id", 1);
        node1.put("pid", null);
        node1.put("value", 1);
        nodes.add(node1);
        Map<String, Object> node2 = new HashMap<>();
        node2.put("id", 2);
        node2.put("pid", 1);
        node2.put("value", 2);
        nodes.add(node2);
        Map<String, Object> node3 = new HashMap<>();
        node3.put("id", 3);
        node3.put("pid", null);
        node3.put("value", 3);
        nodes.add(node3);

        List<Map<String, Object>> tree = buildTree(nodes);
        System.out.println(tree);
    }

    public static List<Map<String, Object>> buildTree(List<Map<String, Object>> nodes) {
        Map<Object, List<Map<String, Object>>> groups = new HashMap<>();
        for (Map<String, Object> node : nodes) {
            Object pid = node.get("pid");
            if (pid == null) {
                pid = "null";
            }
            if (!groups.containsKey(pid)) {
                groups.put(pid, new ArrayList<>());
            }
            groups.get(pid).add(node);
        }
        return buildSubtree(groups, "null");
    }

    private static List<Map<String, Object>> buildSubtree(Map<Object, List<Map<String, Object>>> groups, Object pid) {
        List<Map<String, Object>> children = groups.get(pid);
        if (children == null) {
            return new ArrayList<>();
        }
        List<Map<String, Object>> subtree = new ArrayList<>();
        for (Map<String, Object> child : children) {
            child.put("children", buildSubtree(groups, child.get("id")));
            subtree.add(child);
        }
        return subtree;
    }
}
